package com.drug.mingkang.service.impl;

import com.drug.mingkang.mapper.*;
import com.drug.mingkang.model.*;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.model.vo.ImmPurchaseVo;
import com.drug.mingkang.service.HqImmService;
import com.drug.mingkang.service.HqMarketService;
import com.drug.mingkang.service.ImmPurchaseService;
import com.drug.mingkang.utils.AuditStatus;
import com.drug.mingkang.utils.ExpressageId;
import com.drug.mingkang.utils.ResponseMessage;
import com.drug.mingkang.utils.Tools;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 分公司采购计划单(ImmPurchase)表服务实现类
 *
 * @author wenchangjian
 * @since 2020-08-11 12:00:14
 */
@Service("immPurchaseService")
public class ImmPurchaseServiceImpl implements ImmPurchaseService {

    /**
     * 分公司采购服务
     */
    @Resource
    private ImmPurchaseMapper immPurchaseMapper;

    /**
     * 工具类服务
     */
    @Resource
    private Tools tools;

    /**
     * 分公司采购明细服务
     */
    @Resource
    private ImmPurchaseDeatisMapper immPurchaseDeatisMapper;

    @Resource
    private HqReviewMapper hqReviewMapper;

    /**
     * 分公司管理服务
     */
    @Resource
    private HqImmService hqImmService;

    /**
     * 审核服务
     */
    @Resource
    private AuditRecordMapper auditRecordMapper;

    /**
     * 总公司销售服务
     */
    @Resource
    private HqMarketMapper hqMarketMapper;

    /**
     * 总公司销售明细服务
     */
    @Resource
    private HqMarketdetailMapper hqMarketdetailMapper;

    /**
     * 总公司库存服务
     */
    @Resource
    private HqInventoryMapper hqInventoryMapper;


    /**
     * 分公司采购物流服务
     */
    @Resource
    private ImmTrackingnumberMapper immTrackingnumberMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param purchaseId 主键
     * @return 实例对象
     */
    @Override
    public ImmPurchase queryById(String purchaseId) {
        return this.immPurchaseMapper.queryById(purchaseId);
    }

    /**
     * 查询多条数据
     *
     * @param immPurchaseVo 实例对象
     * @return 对象列表
     */
    @Override
    public Map<String, Object> queryAllByLimit(ImmPurchaseVo immPurchaseVo) {
        return tools.limit(this.immPurchaseMapper.queryAllByLimit(immPurchaseVo), this.immPurchaseMapper.countAudit(immPurchaseVo));
    }

    /**
     * 通过实体作为筛选条件查询
     * @param immPurchaseVo 实例对象
     * @return
     */
    @Override
    public List<ImmPurchase> queryAll(ImmPurchaseVo immPurchaseVo) {
        return this.immPurchaseMapper.queryAll(immPurchaseVo);
    }


    /**
     * 通过实体作为筛选条件查询
     * @author Mr.wang
     * @param immPurchaseVo 实例对象
     * @return
     */
    @Override
    public List<ImmPurchase> queryAll2(ImmPurchaseVo immPurchaseVo) {
        return this.immPurchaseMapper.queryAll2(immPurchaseVo);
    }


    /**
     * 根据条件查询总条数
     * @param immPurchaseVo
     * @return
     */
    @Override
    public int count(ImmPurchaseVo immPurchaseVo) {
        return this.immPurchaseMapper.count(immPurchaseVo);
    }

    /**
     * 新增数据
     *
     * @param immPurchase 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(ImmPurchase immPurchase) {
        return this.immPurchaseMapper.insert(immPurchase);
    }

    /**
     * 修改数据
     *
     * @param immPurchase 实例对象
     * @return 实例对象
     */
    @Override
    public ImmPurchase update(ImmPurchase immPurchase) {
        this.immPurchaseMapper.update(immPurchase);
        return this.queryById(immPurchase.getPurchaseId());
    }

    /**
     * 通过主键删除数据
     *
     * @param purchaseId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String purchaseId) {
        return this.immPurchaseMapper.deleteById(purchaseId) > 0;
    }


    /**
     * 新增或修改采购订单和批量增加采购明细
     * @param immPurchase
     * @return
     */
    @Override
    public int insertSelective(ImmPurchase immPurchase, String arr, HttpSession session) {

        //定义变量rows
        int rows = 0;
        //从session中取用户信息
        PerUsers perUsers = (PerUsers)session.getAttribute("perUsers");
        //如果采购订单ID为空，就增加，否则就修改
        if(StringUtils.isEmpty(immPurchase.getPurchaseId())){
            //从用户信息中获取公司ID设置到对象中
            immPurchase.setImmId(String.valueOf(perUsers.getCompanyId()));

            //定义变量num
            int num = 0;
            //定义变量money
            double money = 0;
            //调用tools工具类中的json转list方法，把传过来的arr转成采购明细list
            List<ImmPurchaseDeatis> list = tools.jsonToList(arr, ImmPurchaseDeatis.class);
            //for循环这个list
            for (ImmPurchaseDeatis immPurchaseDeatis : list){
                //把数量相加得到采购总数量
                num += immPurchaseDeatis.getCount();
                //钱乘以采购数量得到采购总金额
                money += (immPurchaseDeatis.getMoney()*immPurchaseDeatis.getCount());
            }

            //设置采购总数量
            immPurchase.setPurchaseCount(num);
            //设置采购总金额
            immPurchase.setPurchaseMoney(money);
            //设置采购人
            immPurchase.setOperator(perUsers.getUserName());
            //设置备注
            immPurchase.setRemark(immPurchase.getRemark());
            //调用insertSelective方法 新增采购订单
            rows = immPurchaseMapper.insertSelective(immPurchase);

            //循环采购明细集合
            for (ImmPurchaseDeatis li : list) {
                //设置采购明细ID
                li.setPurchaseId(immPurchase.getPurchaseId());
                //设置采购人
                li.setOperator(perUsers.getUserName());
            }
            //调用insertBatch方法 批量增加采购明细
            immPurchaseDeatisMapper.insertBatch(list);
        }else{

            //定义变量num
            int num = 0;
            //定义变量money
            double money = 0;
            //调用tools工具类中的json转list方法，把传过来的arr转成采购明细list
            List<ImmPurchaseDeatis> list = tools.jsonToList(arr, ImmPurchaseDeatis.class);
            //循环采购明细集合
            for (ImmPurchaseDeatis immPurchaseDeatis : list) {
                //把数量相加得到采购总数量
                num += immPurchaseDeatis.getCount();
                //钱乘以采购数量得到采购总金额
                money += (immPurchaseDeatis.getMoney()*immPurchaseDeatis.getCount());
            }
            //设置采购总数量
            immPurchase.setPurchaseCount(num);
            //设置采购总金额
            immPurchase.setPurchaseMoney(money);
            //设置采购人
            immPurchase.setOperator(perUsers.getUserName());
            //设置采购备注
            immPurchase.setRemark(immPurchase.getRemark());
            //调用updateByPurchaseId方法 根据订单ID修改数据
            rows = immPurchaseMapper.updateByPurchaseId(immPurchase);

            //调用deleteById方法 根据采购明细ID把之前的采购明细删掉
            immPurchaseDeatisMapper.deleteById(immPurchase.getPurchaseId());

            //循环采购明细集合
            for (ImmPurchaseDeatis li : list) {
                //设置采购明细ID
                li.setPurchaseId(immPurchase.getPurchaseId());
                //设置采购人
                li.setOperator(perUsers.getUserName());
            }
            //调用insertBatch方法 批量增加采购明细
            immPurchaseDeatisMapper.insertBatch(list);
        }

        //返回变更行数
        return rows;
    }


    /**
     * 修改审核状态
     * @param purchaseId
     * @param status
     * @return
     */
    @Override
    public int fupdate(String purchaseId, String status) {
        return this.immPurchaseMapper.fupdate(purchaseId,status);
    }



    /**
     * 根据采购订单ID查询数据
     * @param purchaseId
     * @return
     */
    @Override
    public ImmPurchase queryByPurchaseId(String purchaseId) {
        return this.immPurchaseMapper.queryByPurchaseId(purchaseId);
    }


    /**
     * 根据订单ID修改数据
     * @param immPurchase
     * @return
     */
    @Override
    public int updateByPurchaseId(ImmPurchase immPurchase) {
        return this.immPurchaseMapper.updateByPurchaseId(immPurchase);
    }

    /**
     * 删除
     * @param purchaseId
     * @return
     */
    @Override
    public int updateIsva(String purchaseId) {
        return immPurchaseMapper.updateIsva(purchaseId);
    }

    /**
     * 根据采购id 修改审核状态
     * @param immPurchaseVo 采购vo
     * @param auditRecord 审核表
     * @param session 当前会话
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage updateStatus(ImmPurchaseVo immPurchaseVo, AuditRecord auditRecord,HttpSession session) {
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        //审核表添加记录
        //添加审核人
        auditRecord.setAuditor(perUsers.getUserName());
        //添加业务id
        auditRecord.setBusinessId(immPurchaseVo.getPurchaseId());
        //根据采购单id查询这批采购单
        ImmPurchase immPurchase = immPurchaseMapper.queryById(immPurchaseVo.getPurchaseId());
        //判断是否为总公司总经理通过 通过往总公司销售保存记录
        if(String.valueOf(AuditStatus.YES_ZGSZJL.status).equals(immPurchaseVo.getIsva())){
            //判断总公司库存是否有足够的库存
            //根据采购单查询采购明细
            List<ImmPurchaseDeatis> purchaseDeatis = immPurchaseDeatisMapper.queryAllByPurchaseId(immPurchaseVo.getPurchaseId());
            for (ImmPurchaseDeatis purchaseDeati : purchaseDeatis) {
                //根据药品id查询库存
                HqInventory hqInventory = hqInventoryMapper.queryByDrugId(purchaseDeati.getDrugId());
                //判断总公司是否具有分公司所采购的药品
                if (StringUtils.isEmpty(hqInventory)) {
                    return ResponseMessage.error("总公司没有此【"+purchaseDeati.getDrugName()+"】药品，请生产此药品！！！");
                }
                //判断分公司此药品采购的数量是否大于总公司此药品库存
                if(purchaseDeati.getCount()>hqInventory.getInventoryNum()){
                    return ResponseMessage.error("总公司此【"+purchaseDeati.getDrugName()+"】药品库存不足，请生产此药品！！！");
                }
            }


            //查找分公司
            HqImm hqImm = hqImmService.queryById(immPurchase.getImmId());
            //保存总公司销售对象
            HqMarket hqMarket = new HqMarket();
            //采购单总金额
            hqMarket.setMarketPrice(immPurchase.getPurchaseMoney());
            //采购总数量
            hqMarket.setMarketNum(immPurchase.getPurchaseCount());
            //采购人
            hqMarket.setMarketMan(perUsers.getUserName());
            //销售给分公司那个订单
            hqMarket.setBranch(immPurchaseVo.getPurchaseId());
            //销售给那额公司
            hqMarket.setRemark("销售给分公司"+hqImm.getImmName());
            //销售人
            hqMarket.setOper(perUsers.getUserName());
            //销售时间
            hqMarket.setMarketTime(new Date());
            //销售状态
            hqMarket.setIsva(Integer.valueOf(immPurchaseVo.getIsva()));
            //添加总公司销售
            hqMarketMapper.insertSelective(hqMarket);

            //根据采购单id查询采购明细
            List<ImmPurchaseDeatis> immPurchaseDetailList = immPurchaseDeatisMapper.queryAllByPurchaseId(immPurchaseVo.getPurchaseId());
            //保存销售明细
            List<HqMarketdetail> list = new LinkedList<HqMarketdetail>();
            for (ImmPurchaseDeatis immPurchaseDeatis : immPurchaseDetailList) {
                HqMarketdetail hqMarketdetail = new HqMarketdetail();
                hqMarketdetail.setDrugId(immPurchaseDeatis.getDrugId());
                hqMarketdetail.setMarketId(hqMarket.getMarketId());
                hqMarketdetail.setNum(immPurchaseDeatis.getCount());
                hqMarketdetail.setPrice(immPurchaseDeatis.getMoney());
                hqMarketdetail.setOper(perUsers.getUserName());
                hqMarketdetail.setRemark(immPurchaseDeatis.getRemark());
                list.add(hqMarketdetail);
            }
            //批量增加销售明细
            hqMarketdetailMapper.insertBatch(list);
            //判断是否为总公司总经理通过 添加物流单号
            //添加物流单号
            ImmTrackingnumber immTrackingnumber = new ImmTrackingnumber();
            //设置采购单id
            immTrackingnumber.setPurchaseId(immPurchase.getPurchaseId());
            //随机生成物流单号
            immTrackingnumber.setTrackingnumber(ExpressageId.experssage());
            //添加物流单
            immTrackingnumberMapper.insertSelective(immTrackingnumber);
        }else if(String.valueOf(AuditStatus.YES_ZGSTG.status).equals(immPurchaseVo.getIsva())){
            //判断是否为总公司总经理通过 添加物流单号
            //添加物流单号
            ImmTrackingnumber immTrackingnumber = new ImmTrackingnumber();
            //设置采购单id
            immTrackingnumber.setPurchaseId(immPurchase.getPurchaseId());
            //随机生成物流单号
            immTrackingnumber.setTrackingnumber(ExpressageId.experssage());
            //添加物流单
            immTrackingnumberMapper.insertSelective(immTrackingnumber);
        }
        //修改审核状态
        immPurchaseMapper.fupdate(immPurchaseVo.getPurchaseId(), immPurchaseVo.getIsva());
        //添加审核记录
        return auditRecordMapper.insertSelective(auditRecord) > 0 ? ResponseMessage.success("审核成功") : ResponseMessage.error("审核失败");
    }

    @Override
    public int countW(ImmPurchaseVo immPurchaseVo) {
        return immPurchaseMapper.countW(immPurchaseVo);
    }

    @Override
    public List<ImmPurchase> queryAllByLimit2(ImmPurchaseVo immPurchaseVo) {
        return this.immPurchaseMapper.queryAllByLimit2(immPurchaseVo);
    }

    @Override
    public int count4(ImmPurchaseVo immPurchaseVo) {
        return this.immPurchaseMapper.count4(immPurchaseVo);
    }


    /**
     * 根据公司ID查询出该公司的所有物流单号
     * @param immPurchaseVo
     * @return
     */
    @Override
    public List<ImmTrackingnumber> selectTrackingNumber(ImmPurchaseVo immPurchaseVo) {
        return this.immPurchaseMapper.selectTrackingNumber(immPurchaseVo);
    }


}